package springboot.springboot06_ssmp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import springboot.springboot06_ssmp.entity.Menu;
import springboot.springboot06_ssmp.mapper.MenuMapper;
import springboot.springboot06_ssmp.service.IMenuService;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author daiqiang
 * @since 2024-06-20
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Override
    public List<Menu> getAllMenu() {
        //一级菜单
        LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Menu::getParentId, 0);
        List<Menu> menuList = this.list(wrapper);
        //填充子菜单
        setMenuChildren(menuList);
        return menuList;
    }
    private void setMenuChildren (List<Menu> menuList){
        if (menuList != null) {
            for (Menu menu : menuList) {
                LambdaQueryWrapper<Menu> subWrapper = new LambdaQueryWrapper<>();
                subWrapper.eq(Menu::getParentId, menu.getMenuId());
                List<Menu> subMenuList = this.list(subWrapper);
                menu.setChildren(subMenuList);
                //递归
                setMenuChildren(subMenuList);
            }


        }

    }
    @Override
    public List<Menu> getMenuListByUserID(Integer userId) {
        //一级菜单
        List<Menu> MenuList =this.baseMapper.getMenuListByUserID(userId,0);
        //子菜单
        setMenuChildrenByUserID(userId,MenuList);
        return MenuList;
    }
    private void setMenuChildrenByUserID (Integer  userId,List<Menu> menuList){
        if (menuList != null) {
            for (Menu menu : menuList) {

                List<Menu> subMenuList = this.baseMapper.getMenuListByUserID(userId,menu.getMenuId());
                menu.setChildren(subMenuList);
                //递归
                setMenuChildrenByUserID(userId,subMenuList);
            }


        }

    }
}
